package com.canbot.u05.activity.attendance;

import android.app.Dialog;
import android.content.Intent;
import android.os.Bundle;
import android.support.design.button.MaterialButton;
import android.support.v7.widget.GridLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.text.TextUtils;
import android.view.View;
import android.widget.Button;

import com.alibaba.fastjson.JSON;
import com.canbot.u05.R;
import com.canbot.u05.activity.BaseActivityNoTitle;
import com.canbot.u05.activity.customvoice.tool.GridSpacingItemDecoration;
import com.canbot.u05.adapter.KqGroupAdapter;
import com.canbot.u05.bean.AttendanceSettings;
import com.canbot.u05.bean.JsonResponse;
import com.canbot.u05.bean.KqGroup;
import com.canbot.u05.bean.PersonGroupData;
import com.canbot.u05.socket.IpMsgConst;
import com.canbot.u05.socket.MsgSendUtils;
import com.canbot.u05.socket.MsgType;
import com.canbot.u05.utils.ConstUtils;
import com.canbot.u05.utils.Logger;
import com.canbot.u05.utils.OkHttpUtils;
import com.canbot.u05.utils.PathConst;
import com.canbot.u05.utils.ToastTools;
import com.canbot.u05.widget.LoadingDialogUtils;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;

/**
 * 考勤分组选择
 */
public class AttendanceGroupActivity extends BaseActivityNoTitle implements View.OnClickListener {

        private static final String TAG = "AttendanceGroupActivity";

        private String[] fileName = new String[]{"rlkxz_u05_001.mp3","rlkxz_u05_002.mp3"};

        private KqGroupAdapter adapter;

        private RecyclerView mRecyclerView;

        private Button btnBack;

        private MaterialButton btnSure;

        private List<KqGroup> data;

        private List<KqGroup> selectList;

        private int lastPosition = -1;

        private String groupId;

        private Dialog dialogLoading;

        private AttendanceSettings attendanceSettings;

        private boolean fromSettings;


        @Override
        protected void onCreate(Bundle savedInstanceState) {
                super.onCreate(savedInstanceState);
                setContentView(R.layout.activity_kq_choose_group);
                selectList = new ArrayList<>();
                setViews();
                int index = (int) (Math.random() * fileName.length);
                boolean isSuccess = MsgSendUtils.sendStringMsg(MsgType.PLAY_SOUND, PathConst.AUDIO_ATTENDANCE_DIR + fileName[index]);
                if (!isSuccess) {
                        ToastTools.newInstance(this).showText(getString(R.string.network_error));
                }

                getDefaultSetting();
        }


        /**
         * 获取之前设置的时间（网络获取）
         */
        private void getDefaultSetting() {
                fromSettings = getIntent().getBooleanExtra("fromSettings",false);
                attendanceSettings = (AttendanceSettings) getIntent().getSerializableExtra("settings");
                Logger.e(TAG, "AttendanceSettings = " + attendanceSettings.toString());
                if (attendanceSettings != null) {
                        groupId = attendanceSettings.getGroupId();
                        if (!TextUtils.isEmpty(groupId)){
                                if (groupId.contains(",")){
                                        //多组
                                        String[]  splits = groupId.split(",");
                                        for (String s :splits){
                                                KqGroup selectGroup = new KqGroup();
                                                selectGroup.setGroupId(Integer.parseInt(s));
                                                selectList.add(selectGroup);
                                        }
                                }else {
                                        //一组
                                        KqGroup selectGroup = new KqGroup();
                                        selectGroup.setGroupId(Integer.parseInt(groupId));
                                        selectList.add(selectGroup);
                                }

                        }
                        Logger.e(TAG,"selectList = " +selectList.toString());
                        if (fromSettings){
                                getGroup();
                        }else {
                                data = new ArrayList<KqGroup>();
                                String json = getIntent().getStringExtra("group_data");
                                Logger.e(TAG,"group_data = " +json);
                                List<KqGroup> list = JSON.parseArray(json,KqGroup.class);
                                Logger.e(TAG,"list = " +list.toString());
                                for (int i = 0; i < list.size(); i++) {
                                        for (int j=0;j<selectList.size();j++){
                                                if (list.get(i).getGroupId() == selectList.get(j).getGroupId()){
                                                        list.get(i).setChecked(true);
                                                        break;
                                                }
                                        }

                                }
                                data.addAll(list);
                                setAdapter(data);
                        }


                }

        }


        /**
         * 获取所有人脸分组
         */
        private void getGroup() {
                dialogLoading = LoadingDialogUtils.createLoadingDialog(this, getString(R.string.attendance_load_tip));
                HashMap<String, Object> hasMap = new HashMap<>();
                hasMap.put("group","");
                OkHttpUtils.upLoadFile("http://" + IpMsgConst.CHEST_SOCKET_HOST + ":7755/" + ConstUtils.URL_GET_FACE_OR_GROUP, hasMap, new OkHttpUtils.OkHttpCallBack() {
                        @Override
                        public void onSuccess(final String result) {

                                Logger.e(TAG, "onSuccess:" + result);
                                runOnUiThread(new Runnable() {
                                        @Override
                                        public void run() {
                                                ToastTools.newInstance(AttendanceGroupActivity.this).showText(getString(R.string.load_success));
                                                LoadingDialogUtils.closeDialog(dialogLoading);
                                                JsonResponse strMsgBean = JSON.parseObject(result, JsonResponse.class);
                                                if (strMsgBean.getRc() == 0) {
                                                        List<PersonGroupData> personGroup = JSON.parseArray(strMsgBean.getResult().toString(), PersonGroupData.class);
                                                        if (personGroup != null && personGroup.size() != 0) {
                                                                data = new ArrayList<KqGroup>();
                                                                KqGroup kqGroup;
                                                                for (int i = 0; i < personGroup.size(); i++) {
                                                                        kqGroup = new KqGroup();
                                                                        kqGroup.setGroupId(personGroup.get(i).getId());
                                                                        kqGroup.setGroupName(personGroup.get(i).getName());
                                                                        for (int j=0;j<selectList.size();j++){
                                                                                if (personGroup.get(i).getId() == selectList.get(j).getGroupId()){
                                                                                        kqGroup.setChecked(true);
                                                                                        break;
                                                                                }
                                                                        }
                                                                        data.add(kqGroup);
                                                                }
                                                                setAdapter(data);
                                                        }
                                                }
                                        }
                                });
                        }

                        @Override
                        public void onFailure() {
                                Logger.e("save", "onFailure");
                                runOnUiThread(new Runnable() {
                                        @Override
                                        public void run() {
                                                LoadingDialogUtils.closeDialog(dialogLoading);
                                                ToastTools.newInstance(AttendanceGroupActivity.this).showText(AttendanceGroupActivity.this.getString(R.string.network_error));
                                        }
                                });
                        }
                });
        }

        private void setAdapter(List<KqGroup> data) {
                adapter = new KqGroupAdapter(AttendanceGroupActivity.this, data);
                mRecyclerView.setAdapter(adapter);
        }

        /**
         * 用户考勤信息显示界面
         */
        private void setViews() {

                btnBack =  findViewById(R.id.imageView_back);
                btnSure = (MaterialButton) findViewById(R.id.btn_sure);
                mRecyclerView =  findViewById(R.id.kq_group_gridView);
                mRecyclerView.setLayoutManager(new GridLayoutManager(this, 5));
                mRecyclerView.addItemDecoration(new GridSpacingItemDecoration(5, 60, false));
                btnBack.setOnClickListener(this);
                btnSure.setOnClickListener(this);

        }


        @Override
        public void onClick(View view) {

                switch (view.getId()) {
                        case R.id.imageView_back:
                                finish();
                                overridePendingTransition(R.anim.face_zoom_enter, R.anim.face_zoom_exit);
                                break;

                        case R.id.btn_sure:
//                                commitData();
                                selectList.clear();
                                selectList.addAll(adapter.getSelected());

                                if (!selectList.isEmpty()){
                                        StringBuilder stringBuilder = new StringBuilder();
                                        for (int i=0;i<selectList.size();i++){
                                                if (i == selectList.size()-1){
                                                        stringBuilder.append(selectList.get(i).getGroupId());
                                                }else {
                                                        stringBuilder.append(selectList.get(i).getGroupId()).append(",");
                                                }

                                        }
                                        attendanceSettings.setGroupId(stringBuilder.toString());
                                        attendanceSettings.setFirstGroupName(selectList.get(0).getGroupName());
                                        Logger.e(TAG,"attendanceSettings  groupid="+stringBuilder.toString());
                                        if (fromSettings){
                                                Intent intent = new Intent();
                                                intent.putExtra("group",JSON.toJSONString(selectList));
                                                setResult(RESULT_OK,intent);
                                                finish();
                                        }else {
                                                Intent intent = new Intent(AttendanceGroupActivity.this,AttendanceSettingTimeActivity.class);
                                                intent.putExtra("settings",attendanceSettings);
                                                startActivity(intent);
                                        }

                                }else {
                                        ToastTools.newInstance(this).showText(getString(R.string.attendance_choose_tip));
                                }
//
                                break;
                }
        }


        @Override
        protected void onPause() {
                if (dialogLoading != null && dialogLoading.isShowing()){
                        LoadingDialogUtils.closeDialog(dialogLoading);
                }
                super.onPause();
        }
}
